#!/usr/bin/env/python3
# -*- coding: utf-8 -*-
from flask import render_template, current_app, jsonify, request, g

from apps.models import Blog, Category
from apps.utils.response_code import RET
from utils.commons import user_login_data
from . import index_blu


# 功能描述: 首页新闻列表获取
# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid,page,per_page
# 返回值: data数据
@index_blu.route('/newslist')
def news_list():
    """
    1.获取参数
    2.参数类型转换,为了分页 做准备,paginate(page,per_page,False)
    3.分页查询
    4.取出分页对象中的属性,总页数,当前页,当前页对象
    5.将当前页对象列表,转成字典列表
    6.返回响应
    :return:
    """
    # 1.获取参数
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    # 2.参数类型转换,为了分页 做准备,paginate(page,per_page,False)
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 10

    # 3.分页查询
    try:
        # 判断是否cid != 1, 不是最新
        filters = []
        if cid != "1":
            filters.append(Blog.category_id == cid)
        paginate = Blog.query.filter(*filters).order_by(Blog.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

    # 4.取出分页对象中的属性,总页数,当前页,当前页对象
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 5.将当前页对象列表,转成字典列表
    newsList = []
    for item in items:
        newsList.append(item.to_dict())

    # 6.返回响应
    return jsonify(errno=RET.OK, errmsg="获取成功", totalPage=totalPage, currentPage=currentPage, newsList=newsList)


@index_blu.route('/')
@user_login_data
def index():
    # 2.1 热门新闻,按照新闻的点击量量,查询前十条新闻
    try:
        news_list = Blog.query.order_by(Blog.clicks.desc()).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

    # 2.2 将新闻列表对象,字典列表对象
    click_news_list = []
    for news in news_list:
        click_news_list.append(news.to_dict())
    # 2.3 查询所有分类信息
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    # 2.4 将分类对象列表,转成字典列表
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())
    # 3.拼接用户数据渲染页面
    data = {
        # 如果user不为空,返回左边的内容, 为空返回右边内容
        "user_info": g.user.to_dict() if g.user else "",
        "click_news_list": click_news_list,
        "categories": category_list
    }

    return render_template('/blog/index.html', data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('blog/favicon.ico')
